﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading;
using System.Transactions;
using Flower.Logging;

namespace Flower.Directory.Util
{
    public static class DemandLock
    {
        private class AutodisposableEvent
        {
            private readonly ManualResetEventSlim _ev;
            private long _refCount;
            private bool _isSet;

            public AutodisposableEvent()
            {
                _ev = new ManualResetEventSlim();
                _refCount = 1;
            }

            public bool IsSet
            {
                get { return _isSet; }
            }

            public void Set()
            {
                lock (this)
                {
                    _isSet = true;
                    _ev.Set();

                    --_refCount;

                    if (_refCount == 0)
                    {
                        _ev.Dispose();
                    }
                }
            }

            public bool Wait(TimeSpan timeout)
            {
                lock (this)
                {
                    if (_isSet)
                    {
                        return true;
                    }

                    ++_refCount;
                }

                bool waitResult = _ev.Wait(timeout);

                lock (this)
                {
                    --_refCount;

                    if (_refCount == 0)
                    {
                        _ev.Dispose();
                    }
                }

                return waitResult;
            }
        }

        private static readonly Log Log = LogManager.CreateLog(typeof(DemandLock).Name);

        private static readonly TimeSpan LockWaitingTimeout = TimeSpan.FromSeconds(30);

        private static readonly Dictionary<string, ConcurrentQueue<AutodisposableEvent>> Locks =
            new Dictionary<string, ConcurrentQueue<AutodisposableEvent>>();
        private static readonly ConcurrentDictionary<string, AutodisposableEvent> TransactionLocks =
            new ConcurrentDictionary<string, AutodisposableEvent>();

        public static void Acquire
        (
            string resource, 
            Action<Transaction> beforeRelease = null,
            Action<Transaction> afterRelease = null, 
            Action<Exception> onError = null
        )
        {
            Transaction ambientTransaction = Transaction.Current;

            if (ambientTransaction == null)
            {
                Log.Warning(string.Format("No ambient transaction. Resource {0} will not be locked.", resource));
                return;
            }

            ConcurrentQueue<AutodisposableEvent> barriersQueue;
            AutodisposableEvent thisBarrier;

            lock (Locks)
            {
                if (!Locks.TryGetValue(resource, out barriersQueue))
                {
                    barriersQueue = new ConcurrentQueue<AutodisposableEvent>();
                    Locks.Add(resource, barriersQueue);
                }

                bool isNew = false;
                thisBarrier = 
                    TransactionLocks.GetOrAdd
                    (
                        string.Concat(ambientTransaction.TransactionInformation.LocalIdentifier, "_", resource),
                        _ => 
                        {
                            isNew = true;
                            return new AutodisposableEvent();
                        }
                    );

                if (isNew)
                {
                    barriersQueue.Enqueue(thisBarrier);

                    ambientTransaction.TransactionCompleted +=
                        (sender, args) =>
                        {
                            try
                            {
                                Log.Trace(() => string.Format("Transaction {0} is completed.", args.Transaction.TransactionInformation.LocalIdentifier));

                                if (beforeRelease != null)
                                {
                                    beforeRelease(args.Transaction);
                                }

                                AutodisposableEvent nextBarrier;

                                while (true)
                                {
                                    if (barriersQueue.TryPeek(out nextBarrier))
                                    {
                                        bool isThisBarrier;

                                        if ((isThisBarrier = ReferenceEquals(thisBarrier, nextBarrier)) || nextBarrier.IsSet)
                                        {
                                            barriersQueue.TryDequeue(out nextBarrier);
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        lock (Locks)
                                        {
                                            if (barriersQueue.Count == 0)
                                            {
                                                Log.Trace(() => string.Format("Lock {0} removed by the transaction {1}.", resource, args.Transaction.TransactionInformation.LocalIdentifier));

                                                Locks.Remove(resource);
                                            }
                                        }

                                        break;
                                    }
                                }

                                thisBarrier.Set();

                                TransactionLocks.TryRemove
                                (
                                    string.Concat(args.Transaction.TransactionInformation.LocalIdentifier, "_", resource),
                                    out nextBarrier
                                );

                                if (afterRelease != null)
                                {
                                    afterRelease(args.Transaction);
                                }
                            }
                            catch (Exception ex)
                            {
                                if (onError != null)
                                {
                                    onError(ex);
                                }
                            }
                        };
                }
            }

            AutodisposableEvent currentBarrier;
            Log.Trace(() => string.Format("Acquiring resource {0} by the transaction {1}.", resource, ambientTransaction.TransactionInformation.LocalIdentifier));

            while 
            (
                barriersQueue.TryPeek(out currentBarrier) && 
                !ReferenceEquals(thisBarrier, currentBarrier)
            )
            {
                Log.Trace(() => string.Format("Transaction {0} is waiting on a barrier.", ambientTransaction.TransactionInformation.LocalIdentifier));
                if (!currentBarrier.Wait(LockWaitingTimeout))
                {
                    throw new TimeoutException("Demanded lock waiting timeout.");
                }
                Log.Trace(() => string.Format("Transaction {0} resumed after waiting.", ambientTransaction.TransactionInformation.LocalIdentifier));
            }
        }
    }
}
